package com.wc.service.impl;

import com.wc.dao.AdminDao;
import com.wc.dao.impl.AdminDaoImpl;
import com.wc.domain.Admin;
import com.wc.service.AdminService;
import com.wc.utils.CreditUtil;
import com.wc.utils.CyptoUtil;

import java.sql.SQLException;

public class AdminServiceImpl implements AdminService {

    private AdminDao adminDao = new AdminDaoImpl();

    @Override
    public Admin login(String account, String password) throws SQLException {
        Admin admin = adminDao.selectByAccount(account);
        //account存在
        if (admin != null) {
            String salt = admin.getSalt();
            String tmp = CyptoUtil.encode(password, salt);
            if (tmp.equals(admin.getPassword())) {
                return admin;
            }
        }
        return null;
    }

    @Override
    public boolean updatePassword(Integer id, String oldPassword, String newPassword) throws SQLException {
        boolean res = false;

        Admin admin = adminDao.selectById(id);
        System.out.println(id);
        System.out.println(admin);
        if (admin != null) {
            //获取用户的原始密码
            String oldEncodePasword = admin.getPassword();

            String tmp = admin.getSalt();

            String password0 = CyptoUtil.decode(oldEncodePasword, tmp);

            System.out.println(password0);
            System.out.println(oldPassword);
            if (!password0.equals(oldPassword)) {
                return res;
            }
            System.out.println(res+"1111");
            //生成新的盐值
            String salt = CreditUtil.genSalt();
            //对原始密码按照新的盐值进行加密
            String newEncodePassword = CyptoUtil.encode(newPassword, salt);
            //将新生成的盐值更新到数据库中
            boolean updateSaltRes = adminDao.updateSalt(id, salt);
            if (!updateSaltRes) {
                return res;
            }
            //更新
            res = adminDao.updatePassword(id, newEncodePassword);
        }
        return res;
    }

    @Override
    public boolean updateAllSaltAndPassword() throws SQLException {
        int res = adminDao.updateAllSaltAndPassword();
        return res == -1 ? true : false;
    }
}
